package com.atguigu.tingshu.order.api;

import com.atguigu.tingshu.common.auth.login.annotation.NeedLogin;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.order.service.OrderInfoService;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import com.atguigu.tingshu.vo.order.TradeVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Tag(name = "订单管理")
@RestController
@RequestMapping("api/order/orderInfo")
@SuppressWarnings({"unchecked", "rawtypes"})
public class OrderInfoApiController {

    @Autowired
    private OrderInfoService orderInfoService;

    // Request URL: http://localhost:8500/api/order/orderInfo/trade
    @PostMapping("trade")
    @Operation(summary = "下单业务")
    @NeedLogin
    public Result trade(@RequestBody @Validated TradeVo tradeVo) {
        OrderInfoVo orderInfoVo = orderInfoService.trade(tradeVo);
        if (!CollectionUtils.isEmpty(orderInfoVo.getExistItemIdList())) {
            throw new GuiguException(201, "已经提交过订单,请勿重复提交！" + orderInfoVo.getExistItemIdList());
        }
        return Result.ok(orderInfoVo);
    }

    // Request URL: http://localhost:8500/api/order/orderInfo/submitOrder
    @PostMapping("submitOrder")
    @Operation(summary = "提交订单")
    @NeedLogin
    public Result submitOrder(@RequestBody @Validated OrderInfoVo orderInfoVo) {
        Map<String,Object> orderMap = orderInfoService.submitOrder(orderInfoVo);
        return Result.ok(orderMap);
    }

    // Request URL: http://localhost:8500/api/order/orderInfo/getOrderInfo/i8fhJYrT8ttm
    @GetMapping("getOrderInfo/{orderNo}")
    @Operation(summary = "根据订单号查询订单信息")
    @NeedLogin
    public Result getOrderInfo(@PathVariable String orderNo) {
        OrderInfo orderInfo = orderInfoService.getOrderInfo(orderNo);
        return Result.ok(orderInfo);
    }

    // Request URL: http://localhost:8500/api/order/orderInfo/findUserPage/1/10
    @GetMapping("findUserPage/{pn}/{pz}")
    @Operation(summary = "分页查询用户订单")
    @NeedLogin
    public Result findUserPage(@PathVariable Long pn,
                               @PathVariable Long pz) {
        IPage<OrderInfo> page = new Page<>(pn,pz);
        page = orderInfoService.findUserPage(page);
        return Result.ok(page);
    }
}

